package com.sduept.nwld.dataview.controller.core;

import com.sduept.cim.ledger.excetpion.ManagementUnitException;
import com.sduept.cim.ledger.manager.SubstationLedgerManager;
import com.sduept.cim.ledger.model.ManagementUnitDict;
import com.sduept.cim.ledger.model.SubstationLedger;
import com.sduept.cim.ledger.services.ManagementUnitService;
import com.sduept.cim.model.core.Substation;
import com.sduept.core.dao.SuperDAO;
import com.sduept.bigdata.web.jsf.controller.AbstractController;
import com.sduept.bigdata.weather.map.MapDataCache;
import com.sduept.nwld.dataserver.manager.cim.CimManager;
import com.sduept.nwld.dataserver.util.LibTreeNode;
import org.apache.commons.lang3.StringUtils;
import org.primefaces.PrimeFaces;
import org.primefaces.event.NodeExpandEvent;
import org.primefaces.event.NodeSelectEvent;
import org.primefaces.event.NodeUnselectEvent;
import org.primefaces.event.SelectEvent;
import org.primefaces.model.DefaultTreeNode;
import org.primefaces.model.TreeNode;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;
import javax.faces.view.ViewScoped;
import javax.inject.Named;
import java.util.*;

/**
 * 调度单位分组的变电站公共弹窗控制器
 *
 * @author huangyu
 */
@Named
@ViewScoped
public class SubstationSelectorController extends AbstractController {
    /**
     *
     */
    private static final long serialVersionUID = 6521386717881334035L;

    @Autowired
    private CimManager cimM;
    @Autowired
    private SubstationLedgerManager stationLedgerM;

    @Autowired
    private ManagementUnitService unitService;
    @Autowired
    private SuperDAO dao;
    @Autowired
    private MapDataCache cc;
    private TreeNode stationRoot; // 变电站选择树
    private TreeNode selectedNode; // 单选择
    private String stationSearch; // 快速筛选变电站
    private Map<String, Substation> stationMap = new HashMap<String, Substation>();

    private TreeNode[] selectedNodes; // 多选择
    private String[] selectedStations;// 传递的已选择变电站id
    private List<Substation> selects = new ArrayList<Substation>();
    private String selectedVol = "500";
    private List<ManagementUnitDict> allDispatchUnits;

    @PostConstruct
    public void init() {
        selectedStations = getParameters("stationIds");
        stationMap = cc.getStationid_map();
        try {
            allDispatchUnits = unitService.getAllDispatchingManagements();
            initStaticStationTree();
        } catch (ManagementUnitException e) {
            e.printStackTrace();
            addErrorMessage("获取所有的调管单位失败");
        }
    }

    /**
     * 初始化变电站选择树，打开页面时候树节点全部加载
     */
    private void initStaticStationTree() {
        stationRoot = new LibTreeNode("Root", null);
        try {
            String rootName = unitService.getManagementUnitRoot();
            if (StringUtils.isEmpty(rootName)) {
                rootName = "南方电网";
            }
            // 组织机构的根节点，即南方电网
            LibTreeNode rootNode = new LibTreeNode("root", rootName, stationRoot);
            // 获取调度单位第一级
            List<ManagementUnitDict> firstLevelChilds = getUnitsByPidFromList(null);
            for (ManagementUnitDict unit : firstLevelChilds) {
                recursionGenChildNode(unit, rootNode);
            }
            rootNode.setExpanded(true);
        } catch (ManagementUnitException e) {
            e.printStackTrace();
            addErrorMessage("获取部门根节点失败");
        }
        stationSearch = null;
    }

    /**
     * 根据pid，从allDispatchUnits中获取pid符合条件的记录
     *
     * @param pid
     * @return
     */
    private List<ManagementUnitDict> getUnitsByPidFromList(String pid) {
        List<ManagementUnitDict> result = new ArrayList<ManagementUnitDict>();
        if (null == pid) {
            for (ManagementUnitDict unit : allDispatchUnits) {
                if (StringUtils.isEmpty(unit.getPid())) {
                    result.add(unit);
                }
            }
        } else {
            for (ManagementUnitDict unit : allDispatchUnits) {
                if (pid.equals(unit.getPid())) {
                    result.add(unit);
                }
            }
        }
        sort(result);
        return result;
    }

    /**
     * 将ManagementUnitDict按ordered从高到低排序
     *
     * @param List<ManagementUnitDict>
     */
    private void sort(List<ManagementUnitDict> list) {
        Collections.sort(list, new Comparator<ManagementUnitDict>() {
            @Override
            public int compare(ManagementUnitDict o1, ManagementUnitDict o2) {
                return o2.getOrdered() - o1.getOrdered();
            }
        });
    }

    /**
     * 递归查找下一级节点，
     *
     * @param dept
     * @param treeNode
     */
    private void recursionGenChildNode(ManagementUnitDict unit, TreeNode rootNode) {
        LibTreeNode treeNode = new LibTreeNode("dispatchUnit", unit, rootNode);
        // 获取该部门下的变电站
        List<SubstationLedger> stationLedgers = stationLedgerM.querySubstationByVoltageAndDispatchUnit(selectedVol, unit);
        for (SubstationLedger ledger : stationLedgers) {
            Substation station = stationMap.get(ledger.getCimId());
            LibTreeNode node = new LibTreeNode("station", station, treeNode);
            if (selectedStations == null) {
                continue;
            }
            for (int i = 0; i < selectedStations.length; i++) {
                if (station.getId().equals(selectedStations[i])) {
                    node.setSelected(true);
                }
            }
        }
        // 获取该部门下的子部门
        List<ManagementUnitDict> childs = getUnitsByPidFromList(unit.getId());
        for (ManagementUnitDict dict : childs) {
            recursionGenChildNode(dict, treeNode);
        }
    }

    /**
     * 选中树节点
     *
     * @param event
     */
    public void onNodeSelect(NodeSelectEvent event) {
        if ("station".equals(event.getTreeNode().getType())) {
            selectedNode = event.getTreeNode();
        }
    }

    /**
     * 选择树节点-多选择器
     */
    public void onStationNodeSelect(NodeSelectEvent event) {
    }

    /**
     * 取消选择树节点-多选择器
     *
     * @param event
     */
    public void onStationNodeUnSelect(NodeUnselectEvent event) {
    }


    /**
     * 展开树节点
     *
     * @param event
     */
    public void onNodeExpand(NodeExpandEvent event) {
    }

    /**
     * 变电站选择树增加快速筛选功能
     *
     * @param event
     */
    public void reGenStationTree(SelectEvent event) {
        Object item = event.getObject();
        if (null != item) {
            stationRoot = new DefaultTreeNode();
            List<Substation> stations = cimM.getStationByName(item.toString());
            for (Substation s : stations) {
                new LibTreeNode("station", s, stationRoot);
            }
        }
    }

    /**
     * 清除快速筛选信息
     */
    public void refreshStationTree() {
        stationSearch = null;
        selectedNode = null;
        initStaticStationTree();
    }

    public void selectSubstation() {
        if (selectedNode != null && "station".equals(selectedNode.getType())) {
            Substation select = (Substation) selectedNode.getData();
            PrimeFaces.current().dialog().closeDynamic(select);
        } else {
            alertErrorMessage("请选择变电站");
        }
    }

    public void selectSubstations() {
        if (null == selectedNodes) {
            PrimeFaces.current().dialog().closeDynamic(selects);
            return;
        }
        selects.clear();
        for (TreeNode tn : selectedNodes) {
            if ("root".equals(tn.getType())) {
                List<TreeNode> cNode = tn.getChildren();
                for (TreeNode treeNode : cNode) {
                    String type = treeNode.getType();
                    if ("dispatchUnit".equals(type)) {
                        addStationByDeptNode(treeNode);
                    } else if ("station".equals(type)) {
                        Substation station = (Substation) tn.getData();
                        if (!selects.contains(station)) {
                            selects.add(station);
                        }
                    }
                }
            }
            if ("dispatchUnit".equals(tn.getType())) {
                addStationByDeptNode(tn);
            } else if ("station".equals(tn.getType())) {
                Substation station = (Substation) tn.getData();
                if (!selects.contains(station)) {
                    selects.add(station);
                }
            }

        }
        PrimeFaces.current().dialog().closeDynamic(selects);
    }

    /**
     * 当前节点类型为"dispatchUnit"
     *
     * @param tn
     */
    private void addStationByDeptNode(TreeNode tn) {
        if ("dispatchUnit".equals(tn.getType())) {
            // 选中了某个部门，即选中了部门下的所有变电站
            // 根据电压等级、部门获取变电站
            ManagementUnitDict dept = (ManagementUnitDict) tn.getData();
            List<SubstationLedger> stationLedgers = stationLedgerM.querySubstationByVoltageAndDispatchUnit(selectedVol, dept);
            for (SubstationLedger ledger : stationLedgers) {
                Substation station = stationMap.get(ledger.getCimId());
                if (!selects.contains(station)) {
                    selects.add(station);
                }
            }
        }
    }

    /**
     * 递归获取子，并将变电站加入集合中
     *
     * @param node
     */
    private void recursionGetStation(TreeNode node) {
        String type = node.getType();
        if ("station".equals(type)) {
            Substation station = (Substation) node.getData();
            if (!selects.contains(station)) {
                selects.add(station);
            }
        } else {
            List<TreeNode> cNodes = node.getChildren();
            for (TreeNode treeNode : cNodes) {
                recursionGetStation(treeNode);
            }
        }
    }

    /**
     * 选择变电站后，重新构造树
     */
    public void changeVoltage() {
        if ("0".equals(selectedVol)) {
            selectedVol = null;
        }
        initStaticStationTree();
    }

    public TreeNode getStationRoot() {
        return stationRoot;
    }

    public void setStationRoot(TreeNode stationRoot) {
        this.stationRoot = stationRoot;
    }

    public TreeNode getSelectedNode() {
        return selectedNode;
    }

    public void setSelectedNode(TreeNode selectedNode) {
        this.selectedNode = selectedNode;
    }

    public String getStationSearch() {
        return stationSearch;
    }

    public void setStationSearch(String stationSearch) {
        this.stationSearch = stationSearch;
    }

    public TreeNode[] getSelectedNodes() {
        return selectedNodes;
    }

    public void setSelectedNodes(TreeNode[] selectedNodes) {
        this.selectedNodes = selectedNodes;
    }

    public String getSelectedVol() {
        return selectedVol;
    }

    public void setSelectedVol(String selectedVol) {
        this.selectedVol = selectedVol;
    }

    public List<Substation> getSelects() {
        return selects;
    }

    public void setSelects(List<Substation> selects) {
        this.selects = selects;
    }

}
